#ifndef ObjectPool_h
#define ObjectPool_h

#include <iostream>
#include <vector>
#include <ctime>
using std::cout;
using std::endl;

template <class T>
class ObjectPool
{
public:
    T* New()
    {
        T* obj = nullptr;
        //优先把还回来的内存对象，再次重复利用
        if(_freeList)
        {
            void *next = *((void**)_freeList);
            obj = (T*)_freeList;
            _freeList = next;
        }
        else
        {
            //当剩余内存块不够一个T对象大小时，重新开辟空间
            if(_remainBytes < sizeof(T))
            {
                _remainBytes = 128 * 1024;
                _memory = (char*)malloc(_remainBytes);   //128kb
                if(_memory == nullptr)
                {
                    throw std::bad_alloc();
                }
            }
            obj = (T*)_memory;
            size_t objSize = sizeof(T) < sizeof(void*) ? sizeof(void*) : sizeof(T); //可在32位和64位机器下运行
            _memory += objSize;
            _remainBytes -= objSize;
        }
        //定位new，显示调用T的构造函数初始化
        new(obj) T;
        return obj;
    }
    void Delete(T* obj)
    {
        //显示调用析构函数清理对象
        obj->~T();
        //将要释放的内存块头插到list中
        *(void**)obj = _freeList;   //由obj前4or前8个字节记录下一个释放内存块的地址。可在32位和64位机器下运行
        _freeList = obj;
    }
private:
    char *_memory = nullptr;  //大块内存指针。char类型方便对池中内存切分
    size_t _remainBytes = 0;    //大块内存在切分过程中剩余字节数
    void *_freeList = nullptr; //用于管理释放回来的内存块。使用单链表管理。每个内存块需要储存下一个内存块的地址。
};

struct TreeNode
{
    int _val;
    TreeNode* _left;
    TreeNode* _right;

    TreeNode()
        :_val(0)
        , _left(nullptr)
        , _right(nullptr)
    {}
};

void TestObjectPool()
{
    // 申请释放的轮次
    const size_t Rounds = 5;

    // 每轮申请释放多少次
    const size_t N = 100000;

    std::vector<TreeNode*> v1;
    v1.reserve(N);

    size_t begin1 = clock();
    for (size_t j = 0; j < Rounds; ++j)
    {
        for (int i = 0; i < N; ++i)
        {
            v1.push_back(new TreeNode);
        }
        for (int i = 0; i < N; ++i)
        {
            delete v1[i];
        }
        v1.clear();
    }

    size_t end1 = clock();

    std::vector<TreeNode*> v2;
    v2.reserve(N);

    ObjectPool<TreeNode> TNPool;
    size_t begin2 = clock();
    for (size_t j = 0; j < Rounds; ++j)
    {
        for (int i = 0; i < N; ++i)
        {
            v2.push_back(TNPool.New());
        }
        for (int i = 0; i < N; ++i)
        {
            TNPool.Delete(v2[i]);
        }
        v2.clear();
    }
    size_t end2 = clock();

    cout << "new cost time:" << end1 - begin1 << endl;
    cout << "object pool cost time:" << end2 - begin2 << endl;
}

#endif /* ObjectPool_h */
